<?php

/**
 * TextosController
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class TextosController extends Zend_Controller_Action {
	
	private $usuario;
	private $textosDAO;
	private $imagensDAO;
	private $perfil;
	
	protected $_acl;
	protected $_session;
	
	public function init() {
		$config = Zend_Registry::get ( 'config' );
		$this->_acl = $this->getFrontController ()->getParam ( 'acl' );
		$this->_session = new Zend_Session_Namespace ( $config->session->namespace );
		$this->usuario = $this->_session->storage;
		
		$this->textosDAO  = new Textos ();
		$this->imagensDAO = new Imagens();
		
		if (! ( $this->usuario )) {
			$this->perfil = "visitante";
		} else {
			$this->perfil = $this->usuario->perfil;
		}

		$this->view->perfil = $this->perfil;
		$this->view->aba = 'pesquisar_textos';
	}
	
	public function preDispatch() {

		if (! Zend_Auth::getInstance ()->hasIdentity ()) {
			$this->view->logado = 0;
			
		} else {
			$config = Zend_Registry::get ( 'config' );
			$this->_session = new Zend_Session_Namespace ( $config->session->namespace );
			$this->_usuario = $this->_session->storage;
			$this->view->logado = 1;
		}
	
	}
	
	public function indexAction() {
		
		$params = new Zend_Filter_Input ( null, null, $this->getRequest ()->getParams () );
		$busca = $params->busca;
		$areas = $params->areas;
		$page = $params->page;
		
		if (isset ( $busca ) || (isset ( $areas ) && $areas != 0)) {
			$page = 1;
		} else if (! isset ( $page ) && $this->_session->page) {
			$page = $this->_session->page;
		} else {
			$this->_session->page = $page;
		}
		
		if (! isset ( $busca )) {
			$busca = $this->_session->busca;
		} else {
			$this->_session->busca = $busca;
		}
		
		$this->view->busca = $busca;
		
		if (! isset ( $areas )) {
			$areas = $this->_session->areas;
		} else {
			$this->_session->areas = $areas;
		}
		
		$this->view->area = $areas;
		
		if( $params->filtro && $params->ordem){ 
			$filtro = $params->filtro;
			$ordem = $params->ordem;
			$textos = $this->textosDAO->findByFiltro($filtro, $ordem);
		}
			
			
		elseif(! isset($busca)){
			$textos = $this->textosDAO->findByFiltro('titulo', 'asc'); 
			$ordem = 'asc';
		}
		else 
			$textos = $textos = $this->textosDAO->search($busca, $areas);
		
		$this->view->textos = $textos;
		
		$paginator = Zend_Paginator::factory ( $textos );
		
		$paginator->setItemCountPerPage ( 10 );
		
		if ($page)
			$paginator->setCurrentPageNumber($page);
				
		$paginator->setPageRange ( range ( 1, 5 ) );
		Zend_View_Helper_PaginationControl::setDefaultViewPartial ( "_partials/paginacao.phtml" );
		
		$this->view->paginator = $paginator;
		
		$this->view->textos = $textos;
		
		if(isset($ordem))
			$this->view->ordem = $ordem;
		
		$this->view->perfil = $this->perfil;
		
		$this->view->aba = 'pesquisar_textos';
		
		$areas = new Areas ( );
		$this->view->areas = $areas->fetchAll ();
	
	}
	
	public function verAction() {
		
		if($this->perfil != 'professor') 
			$this->view->aba = 'pesquisar_textos';
		else $this->view->aba = 'admintextos';
		$params = new Zend_Filter_Input ( null, null, $this->getRequest ()->getParams () );
		$filtro = new Zend_Filter_Int ( );
		$id = $filtro->filter ( $params->id );
		$textoDAO = new Textos ( );
		$texto = $textoDAO->find ( $id )->current ();
		$this->view->texto = $texto;
		
		$imagens = $this->imagensDAO->fetchAll("id_texto = $id");
		$this->view->imgs = $imagens;
		
		$texto_completo = utf8_encode($texto->texto);
		$texto_aux = $this->view->Br2nl(utf8_decode($texto_completo));
		$lacunasDAO = new Lacunas ( );
		$lacunas = $lacunasDAO->findByTexto ( $texto->id );
		
		/*
		 * Carregando as lacunas de acordo com os recursos
		 * Associacao de lacunas ou
		 * Preenchimento de lacunas normal
		 */
		
		$novotexto = "";
		$parou = null;
		
		if (count ( $lacunas ) > 0) {
			$this->view->lacunas = $lacunas;
			if (isset ( $this->usuario->id ) || $this->perfil == 'visitante') {
				foreach ( $lacunas as $l ) {
					if ($textoDAO->hasRecurso ('lacunas_associacao', $id)) {
						$form_lacuna = $this->getAssocLacuna ( $l->id, @$this->usuario->id );
						$this->view->lacunas_associacao = true;							
					} else {
						$form_lacuna = $this->getFormLacuna ( $l->id, @$this->usuario->id );
					}
					
					if (! isset ( $parou ))
						$parou = 0;
					
					$pedaco = substr ( $texto_aux, $parou, ($l->fim - $parou) );
					$parou = $l->fim;
					$pedaco = substr_replace ( $pedaco, $form_lacuna, ($l->inicio - $parou), ($l->fim - $l->inicio) );
					$novotexto .= $pedaco;
				
				}
				$novotexto .= substr ( $texto_aux, $parou );
			
			}
		} else { 
			$novotexto = $texto_completo;
		}
		
		
		
		if (isset ( $this->usuario->id ))
			$this->view->usuario = $this->usuario->id;
		$this->view->texto_completo = utf8_encode(nl2br ( $novotexto ));
		
		
		/* Recursos de Questionarios */
		$repository = new Perguntas();
		$perguntas = $repository->findByTexto($texto->id);
		$this->view->perguntas = $perguntas;

		if (count($this->view->perguntas) || (count($this->view->lacunas) && $this->view->lacunas_associacao)) {
			$this->view->boxLateral = true;
		}
		
		if ($this->view->boxLateral) {
			$textClass = "texto_menor";
		} else {
			$textClass = "texto";
		}
		
		$this->view->textClass = $textClass;
	}
	
	public function getFormLacuna($id, $usuario) {
		$lacunasTentativasDAO = new LacunasTentativas ( );
		$lacunasTentativas = $lacunasTentativasDAO->findByLacunaAndUsuario ( $id, $usuario );
		$lacunasDAO = new Lacunas ( );
		$lacuna = $lacunasDAO->find ( $id )->current ();
		//if (isset ( $lacunasTentativas->acertou ) && $lacunasTentativas->acertou == 1) {
			//$classe = 'lacuna_certa';
			//$complemento = '';
			//$atributos = "value=\"{$lacuna->palavra}\" disabled=\"true\" ";
			$atributos = "";
		//}else{
			$classe = 'lacuna';
			$complemento = '';
			if ($this->perfil != 'visitante')
			$complemento = "<input value=\"ok\" id='{$id}' name='ok[{$id}]' class=\"testar_lacuna\" type=\"button\"  />";
		//}
		$form = "<input type=\"text\" ";
		if (isset ( $atributos ))
			$form .= $atributos;
		$form .= " id=\"lacuna[$id]\" class=\"{$classe}\" name=\"lacunas[{$id}]\" /><a href='{$this->view->baseUrl}/lacunas/ver/id/$id?width=640&height=400' class='thickbox'><img border='0' style='position: relative; top: 5px;'  src='" . $this->view->publicUrl . "/imagens/interrogacao.gif' alt='veja as dicas sobre esta lacuna' title='veja as dicas sobre esta lacuna' /></a>{$complemento}";
		
		return $form;
	}
	
	public function getAssocLacuna($id) {
		$lacunasDAO = new Lacunas ( );
		$lacuna = $lacunasDAO->find ( $id )->current ();
		
		$dropzone = "<span class=\"divDrop\" id=\"{$lacuna->id}\"></span><a href=\"{$this->view->baseUrl}/lacunas/ver/id/$id?width=640&height=400\" class=\"thickbox\"><img border='0'  src='" . $this->view->publicUrl . "/imagens/interrogacao.gif' alt='veja as dicas sobre esta lacuna' title='veja as dicas sobre esta lacuna' /></a>";
		return $dropzone;
	}
	
	public function validarAction() {
		$id_lacuna = ( int ) $_REQUEST ['id'];
		$valor = $_REQUEST ['valor'];
		$usuario = $_REQUEST ['usuario'];
		
		$lacunaDAO = new Lacunas ( );
		$lacuna = $lacunaDAO->find ( $id_lacuna )->current ();
		$lacuna->palavra = utf8_encode($lacuna->palavra);
		if (strcasecmp ( trim ( $lacuna->palavra ), $valor ) == 0) {
			$lacunasTentativasDAO = new LacunasTentativas ( );
			$lacunasTentativas = $lacunasTentativasDAO->findByLacunaAndUsuario ( $id_lacuna, $usuario );
			if($lacunasTentativas->tentativas >= 1){
				$retorno = array ('msg' =>   'Parabéns! Você acertou depois de ' . ($lacunasTentativas->tentativas + 1 ). ' tentativa(s)!' , 'acertou' => 1 );
			}
			else{
				$retorno = array ('msg' =>  'Parabéns! Você acertou com 1 tentativa!','acertou' => 1);
			} 
			$lacunaDAO->confirmaAcerto ( $id_lacuna, $usuario );
		} else {
			$retorno = array ('msg' => 'Tentativa errada!', 'acertou' => 0 );
			$lacunaDAO->adicionaTentativa ( $id_lacuna, $usuario );
		}
		
		print Zend_Json::encode ( $retorno );
		exit ();
	
	}
	
	public function validarassocAction() {
		$id_lacuna = ( int ) $_REQUEST ['id'];
		$valor = $_REQUEST ['valor'];
		$usuario = $_REQUEST ['usuario'];
		
		$lacunaDAO = new Lacunas ( );
		$lacuna = $lacunaDAO->find ( $id_lacuna )->current ();
		$lacuna->palavra = utf8_encode($lacuna->palavra);
		if (strcasecmp ( $lacuna->palavra , $valor ) != 0) {
			$retorno = array ( 'id_lacuna' =>  $id_lacuna, 'lacuna' => $valor,  'acertou' => 0 );
			$lacunaDAO->adicionaTentativa ( $id_lacuna, $usuario );
		}
		
		print Zend_Json::encode ( $retorno );
		exit ();
		
	}
	
	public function testeAction() {
	
	}

	public function admineditarAction(){
		print "oi";
		exit();
	}
}
